/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package library.gui.edit;


import java.net.ConnectException;
import javax.xml.ws.soap.SOAPFaultException;
import library.gui.ConnectionHolder;
import library.gui.tools.Memento;
import library.gui.tools.Tools;
import library.gui.models.BookAvailabilityBoxModel;
import library.gui.models.BookTableModel;
import library.gui.models.DepartmentBoxModel;
import library.webservice.BookDTO;
import library.webservice.BookStatus;
import library.webservice.Department;
import library.webservice.IllegalArgumentException_Exception;


/**
 *
 * @author Emptak,Andrej
 */
public class EditBookDialog extends javax.swing.JDialog {

    private BookDTO bookDTO;
    private ConnectionHolder holder;
    private BookTableModel btm;
    private Memento<BookDTO> memento = new Memento<>();
    
    
    public void setReq(BookDTO bookDTO,ConnectionHolder holder,BookTableModel btm)
    {
        this.bookDTO = bookDTO;
        this.holder = holder;
        this.btm = btm;
        memento.setState(bookDTO);
        valuesFromObject(bookDTO);
    }
    
    /**
     * Takes values from combo boxes text fields into given object
     * @param b 
     */
    private void valuesToObject(BookDTO b)
    {
        b.setAuthor(jTextFieldBookAuthor.getText());
        b.setBookID(new Long(jTextFieldBookID.getText()));
        b.setBookStatus(BookStatus.valueOf(jComboBoxAvailability.getSelectedItem().toString()));
        b.setDepartment(Department.valueOf(jComboBoxDepartment.getSelectedItem().toString()));
        b.setTitle(jTextFieldBookTitle.getText());     
    }
    
    /**
     * Sets values into comboboxes and textfields from given object
     * @param b 
     */
    private void valuesFromObject(BookDTO b)
    {
        jTextFieldBookID.setText(b.getBookID().toString());
        jTextFieldBookTitle.setText(b.getTitle());
        jTextFieldBookAuthor.setText(b.getAuthor());
        jComboBoxAvailability.setSelectedItem(b.getBookStatus());
        jComboBoxAvailability.setSelectedItem(b.getDepartment());
    }
    
    private void updateModel()
    {
        btm.clear();
        try
        {
            btm.addBooks(holder.getBws().getAllBooks());            
        }
        catch(ConnectException ce)
        {
            System.err.println(ce.getMessage());
        }        
    }
    
    /**
     * Creates new form EditBookDialog
     */
    public EditBookDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelBookEditTitle = new javax.swing.JLabel();
        jLabelBookID = new javax.swing.JLabel();
        jLabelBookTitle = new javax.swing.JLabel();
        jLabelBookAuthor = new javax.swing.JLabel();
        jLabelDepartment = new javax.swing.JLabel();
        jLabelStatus = new javax.swing.JLabel();
        jTextFieldBookID = new javax.swing.JTextField();
        jTextFieldBookTitle = new javax.swing.JTextField();
        jTextFieldBookAuthor = new javax.swing.JTextField();
        jButtonReset = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jComboBoxAvailability = new javax.swing.JComboBox();
        jComboBoxDepartment = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("Messages"); // NOI18N
        setTitle(bundle.getString("gui.frame.books.button.edit")); // NOI18N

        jLabelBookEditTitle.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabelBookEditTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelBookEditTitle.setText(bundle.getString("gui.frame.books.button.edit")); // NOI18N

        jLabelBookID.setText(bundle.getString("gui.book.bookid")); // NOI18N

        jLabelBookTitle.setText(bundle.getString("gui.book.title")); // NOI18N

        jLabelBookAuthor.setText(bundle.getString("gui.book.author")); // NOI18N

        jLabelDepartment.setText(bundle.getString("gui.book.department")); // NOI18N

        jLabelStatus.setText(bundle.getString("gui.book.availability")); // NOI18N

        jTextFieldBookID.setText(bundle.getString("gui.field.error")); // NOI18N
        jTextFieldBookID.setEnabled(false);

        jTextFieldBookTitle.setText(bundle.getString("gui.field.error")); // NOI18N

        jTextFieldBookAuthor.setText(bundle.getString("gui.field.error")); // NOI18N

        jButtonReset.setText(bundle.getString("gui.button.reset")); // NOI18N
        jButtonReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonResetActionPerformed(evt);
            }
        });

        jButton1.setText(bundle.getString("gui.button.edit")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jComboBoxAvailability.setModel(new BookAvailabilityBoxModel());

        jComboBoxDepartment.setModel(new DepartmentBoxModel());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelBookEditTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelDepartment)
                                    .addComponent(jLabelStatus))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jComboBoxAvailability, 0, 261, Short.MAX_VALUE)
                                    .addComponent(jComboBoxDepartment, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelBookID)
                                    .addComponent(jLabelBookTitle)
                                    .addComponent(jLabelBookAuthor))
                                .addGap(30, 30, 30)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextFieldBookAuthor)
                                    .addComponent(jTextFieldBookTitle)
                                    .addComponent(jTextFieldBookID))))
                        .addGap(19, 19, 19)))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(112, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(27, 27, 27)
                .addComponent(jButtonReset)
                .addGap(116, 116, 116))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabelBookEditTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelBookID)
                    .addComponent(jTextFieldBookID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelBookTitle)
                    .addComponent(jTextFieldBookTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelBookAuthor)
                    .addComponent(jTextFieldBookAuthor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxDepartment, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelDepartment))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxAvailability, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabelStatus))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonReset)
                    .addComponent(jButton1))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
             
        valuesToObject(this.bookDTO);
        
        try
        {
            holder.getBws().updateBook(this.bookDTO);
            updateModel();
            System.out.print("==Following book has been updated:");
            Tools.printEntity(bookDTO);
            dispose();            
        }
        catch(ConnectException | SOAPFaultException | IllegalArgumentException_Exception | IllegalArgumentException | NullPointerException e)
        {
            System.err.println(e.getMessage());
            Tools.createErrorDialog(e.getMessage());
        }  
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButtonResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonResetActionPerformed
        this.bookDTO = memento.getFirstState();
        valuesFromObject(this.bookDTO);        
    }//GEN-LAST:event_jButtonResetActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditBookDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditBookDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditBookDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditBookDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                EditBookDialog dialog = new EditBookDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonReset;
    private javax.swing.JComboBox jComboBoxAvailability;
    private javax.swing.JComboBox jComboBoxDepartment;
    private javax.swing.JLabel jLabelBookAuthor;
    private javax.swing.JLabel jLabelBookEditTitle;
    private javax.swing.JLabel jLabelBookID;
    private javax.swing.JLabel jLabelBookTitle;
    private javax.swing.JLabel jLabelDepartment;
    private javax.swing.JLabel jLabelStatus;
    private javax.swing.JTextField jTextFieldBookAuthor;
    private javax.swing.JTextField jTextFieldBookID;
    private javax.swing.JTextField jTextFieldBookTitle;
    // End of variables declaration//GEN-END:variables
}
